Skip to content

feat: email query param override for chat#1647

Merged
sweetmantech merged 20 commits intotestfrom
feature/rec-52-email-override
Apr 6, 2026
Merged

feat: email query param override for chat#1647
sweetmantech merged 20 commits intotestfrom
feature/rec-52-email-override

Conversation

@recoup-coding-agent
Copy link
Copy Markdown
Collaborator

@recoup-coding-agent recoup-coding-agent commented Apr 6, 2026

Summary

  • Reads email query param from the chat/landing page URLs
  • Threads the email through HomePage → Chat → VercelChatProvider → useVercelChat
  • Includes email in the /api/chat request body when present
  • Enables admins/org members to view customer chat experiences via ?email=customer@example.com

Test plan

  • Verify ?email=customer@example.com passes the email in the API request body
  • Verify no email is sent when query param is absent
  • Verify existing chat functionality is unaffected

🤖 Generated with Claude Code


Summary by cubic

Adds an optional email query param to preview customer chats (REC-52). Resolves it to an accountId on the client, stores a session override, injects it into /api/chat, and shows a top “Viewing as {email}” badge with one‑click clear.

  • Refactors

    • Replaced AccountOverrideSync with AccountOverrideProvider that reads ?email=, resolves via GET /api/accounts/{email} using @tanstack/react-query + @privy-io/react-auth, and persists to sessionStorage under ACCOUNT_OVERRIDE_STORAGE_KEY (supports ?email=clear).
    • useVercelChat now consumes useAccountOverride() to include accountId in the chat body. Added AccountOverrideBadge in app/layout.tsx. Extracted fetchAccountIdByEmail to lib/accounts/.
    • Split storage helpers into getStoredAccountOverride, setStoredAccountOverride, and clearStoredAccountOverride; moved them to lib/accounts/override/. Storage sync now happens in the useQuery queryFn (no useEffect).
  • Bug Fixes

    • Safely handle array-valued q and email search params by using the first value.
    • Improve badge contrast, including brighter amber-400 in dark mode.
    • fetchAccountIdByEmail: throw on non-404 HTTP errors so @tanstack/react-query can retry or surface errors.

Written for commit cfb889e. Summary will update on new commits.

Summary by CodeRabbit

Release Notes

  • New Features
    • Chat now supports email parameter, allowing users to associate their email address with chat sessions for improved tracking and communication.

Read email query param from URL on chat/landing pages and thread it
through the component tree to include in the /api/chat request body.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
@vercel
Copy link
Copy Markdown
Contributor

vercel bot commented Apr 6, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
recoup-chat Ready Ready Preview Apr 6, 2026 11:19pm

Request Review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 6, 2026

Warning

Rate limit exceeded

@sweetmantech has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 10 minutes and 38 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 10 minutes and 38 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d72ebc5c-6bff-4589-adfe-18c982c9d564

📥 Commits

Reviewing files that changed from the base of the PR and between 7d30205 and 0aab24f.

📒 Files selected for processing (7)
  • app/layout.tsx
  • components/AccountOverrideBadge.tsx
  • hooks/useVercelChat.ts
  • lib/accounts/fetchAccountIdByEmail.ts
  • lib/consts.ts
  • providers/AccountOverrideSync.tsx
  • providers/Providers.tsx
📝 Walkthrough

Walkthrough

Email parameter support is added across the chat application's entire stack. The email query parameter is extracted from URL searchParams at the page level, then propagated through the component hierarchy and hooks, ultimately being included in chat request bodies sent to the API.

Changes

Cohort / File(s) Summary
Page-level Email Extraction
app/chat/page.tsx, app/page.tsx
Both pages now await searchParams into a local variable and extract optional email via params?.email, forwarding it to their respective child components (Chat and HomePage).
Component Layer Forwarding
components/Home/HomePage.tsx, components/VercelChat/chat.tsx
Both components now accept an optional email?: string prop and forward it downstream to their children (Chat and VercelChatProvider respectively).
Hook & Provider Implementation
hooks/useVercelChat.ts, providers/VercelChatProvider.tsx
Both accept optional email and thread it through: VercelChatProvider passes email to useVercelChat, which conditionally includes it in the chatRequestBody sent to useChat, with email added to the memoization dependency array.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Suggested reviewers

  • sweetmantech

Poem

📧 Through layers neat, the email flows,
From query string to depths it goes,
Each component hands it down,
Till the request wears the crown! ✨

🚥 Pre-merge checks | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Solid & Clean Code ⚠️ Warning The pull request violates the DRY principle with identical query parameter extraction logic duplicated in both files, and violates type safety by using unsafe assertions without handling array values. Create a reusable utility function in lib/searchParams/parseSearchParams.ts that safely extracts parameters using Array.isArray(value) ? value[0] : value pattern, then replace duplicated logic in both files.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/rec-52-email-override

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
app/page.tsx (1)

11-18: Consider extracting shared param parsing logic.

Both app/page.tsx and app/chat/page.tsx have nearly identical param extraction logic. For DRY compliance and consistent behavior, consider extracting a utility function.

♻️ Optional: Shared utility extraction
// lib/parseSearchParams.ts
export function parseSearchParams(params: Record<string, string | string[] | undefined> | undefined) {
  const getString = (key: string) => {
    const value = params?.[key];
    return Array.isArray(value) ? value[0] : value;
  };
  
  return {
    initialMessage: getString('q'),
    email: getString('email'),
  };
}

Then in both pages:

const params = await searchParams;
const { initialMessage, email } = parseSearchParams(params);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/page.tsx` around lines 11 - 18, The param parsing in Home (function Home
in app/page.tsx) duplicates logic used in app/chat/page.tsx; extract this into a
shared utility (e.g., parseSearchParams) that accepts the searchParams object
and returns { initialMessage, email } using a helper to normalize
string|string[] values, then update Home to call parseSearchParams(await
searchParams) and pass the returned initialMessage into getMessages and email
into HomePage; ensure generateUUID() and getMessages(...) usage remains
unchanged and only the params extraction is moved to the new utility.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@app/chat/page.tsx`:
- Around line 13-16: The code currently asserts searchParams values as strings
which breaks if params are arrays; normalize values first by checking
Array.isArray on params?.q and params?.email and extracting the first element
(or undefined) before calling getMessages or using email, e.g., compute a
safeInitialMessage and safeEmail from params and pass safeInitialMessage to
getMessages so downstream code only ever receives string | undefined rather than
string | string[].

In `@app/page.tsx`:
- Around line 13-16: The code assumes searchParams keys are strings but may be
arrays; update how params is read so initialMessage and email handle array
values safely: when retrieving params (the const params, usage of initialMessage
and email) coerce params?.q and params?.email to strings by checking if they are
arrays (e.g., Array.isArray) and picking the first element or joining as needed,
then pass that sanitized string into getMessages(initialMessage) and any
downstream logic; ensure getMessages is called only with a string and email is
typed as string | undefined after normalization.

---

Nitpick comments:
In `@app/page.tsx`:
- Around line 11-18: The param parsing in Home (function Home in app/page.tsx)
duplicates logic used in app/chat/page.tsx; extract this into a shared utility
(e.g., parseSearchParams) that accepts the searchParams object and returns {
initialMessage, email } using a helper to normalize string|string[] values, then
update Home to call parseSearchParams(await searchParams) and pass the returned
initialMessage into getMessages and email into HomePage; ensure generateUUID()
and getMessages(...) usage remains unchanged and only the params extraction is
moved to the new utility.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5dae6817-3948-4c52-b911-349cf7950e44

📥 Commits

Reviewing files that changed from the base of the PR and between 4c5c3fe and 7d30205.

📒 Files selected for processing (6)
  • app/chat/page.tsx
  • app/page.tsx
  • components/Home/HomePage.tsx
  • components/VercelChat/chat.tsx
  • hooks/useVercelChat.ts
  • providers/VercelChatProvider.tsx

Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 6 files

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Requires human review: Modifies the core chat API request body to include an email override for user impersonation/context, which has security and authorization implications requiring human review.

Use Array.isArray checks instead of type assertions for q and email
search params to handle duplicate query param edge case.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 2 files (changes from recent commits).

Requires human review: This PR introduces a user context override via query parameters (email), which is a security-sensitive change that modifies API request bodies and requires human verification of authorization logic.

…/{email}

Instead of passing email to /api/chat, the Chat component resolves
email → accountId using the new accounts endpoint, then passes
accountId in the chat body using the existing override mechanism.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3 issues found across 4 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="hooks/useVercelChat.ts">

<violation number="1" location="hooks/useVercelChat.ts:174">
P2: `accountIdOverride` in the request body will be ignored for authenticated users because the server always overwrites `accountId` with the header-derived value. The override feature won’t take effect unless the backend accepts an explicit override field or conditional logic.</violation>
</file>

<file name="hooks/useEmailAccountId.ts">

<violation number="1" location="hooks/useEmailAccountId.ts:18">
P2: Reset the accountId when `email` is missing or changes; otherwise the hook can return a stale accountId from a prior email.</violation>

<violation number="2" location="hooks/useEmailAccountId.ts:36">
P2: Effect lacks cancellation or latest-email check, so slower responses can overwrite accountId with stale data after email changes.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review, or fix all with cubic.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DRY - does this match how we accept the api override query param? We should keep page query param override management consistent.

id: string;
reportId?: string;
initialMessages?: UIMessage[];
email?: string;
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How can we eliminate prop drilling of the email param?

}, [email, getAccessToken]);

return accountId;
}
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DRY - is this following the same architecture as the api query param?

sweetmantech and others added 3 commits April 6, 2026 17:31
Follow the ApiOverrideSync pattern: AccountOverrideSync reads ?email=
query param, resolves it to an accountId via GET /api/accounts/{email},
and stores it in session storage. useVercelChat reads the override from
session storage. No prop drilling through 6 files.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
const searchParams = useSearchParams();
const { getAccessToken } = usePrivy();

useEffect(() => {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would this be more efficient using tanstack useQuery?

>
<WagmiProvider>
<PrivyProvider>
<AccountOverrideSync />
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this provider at a different level than ApiOverrideSync?

sweetmantech and others added 2 commits April 6, 2026 17:34
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Replaces manual useEffect fetch with useQuery for caching and
deduplication. Added comment explaining why placement differs from
ApiOverrideSync (needs usePrivy for auth).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

const { data: accountId } = useQuery({
queryKey: ["accountOverride", emailParam],
queryFn: async () => {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this query fn be moved to a lib file to follow SRP?

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 2 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="lib/accounts/fetchAccountIdByEmail.ts">

<violation number="1" location="lib/accounts/fetchAccountIdByEmail.ts:20">
P1: Only treat 404 as “not found”; other HTTP errors should be surfaced instead of being silently converted to null.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review, or fix all with cubic.

Shows a fixed pill at the top center with "Viewing as {email}" and an X
button to clear the override when ?email= is active.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Comment on lines +13 to +28
const searchParams = useSearchParams();
const router = useRouter();
const [isActive, setIsActive] = useState(false);
const email = searchParams.get("email");

useEffect(() => {
if (!email || email === "clear") {
setIsActive(false);
return;
}

const accountId = window.sessionStorage.getItem(
ACCOUNT_OVERRIDE_STORAGE_KEY,
);
setIsActive(!!accountId);
}, [email]);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dry - why isn't this using the existing provider?

Reads from the same queryKey as AccountOverrideSync instead of
duplicating session storage checks.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Comment on lines +20 to +29
const { data: accountId } = useQuery({
queryKey: ["accountOverride", email],
queryFn: async () => {
const accessToken = await getAccessToken();
if (!accessToken) return null;
return fetchAccountIdByEmail(email!, accessToken);
},
enabled: !!email && email !== "clear",
staleTime: Infinity,
});
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DRY - why do we need this useQuery instead of using the existing provider?

Badge polls session storage instead of duplicating the useQuery.
AccountOverrideSync writes it, badge reads it.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@cubic-dev-ai
Copy link
Copy Markdown

cubic-dev-ai bot commented Apr 6, 2026

You're iterating quickly on this pull request. To help protect your rate limits, cubic has paused automatic reviews on new pushes for now—when you're ready for another review, comment @cubic-dev-ai review.

No polling or state needed — if ?email= is in the URL, show the badge.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@sweetmantech
Copy link
Copy Markdown
Collaborator

Browser Testing Results (Preview Deployment)

Preview URL: recoup-chat-git-feature-rec-52-email-5e5d60-recoupable-ad724970.vercel.app

?email=jessica@rostrumrecords.com

  • AccountOverrideBadge shows "Viewing as jessica@rostrumrecords.com" pill at top center
  • X button visible for clearing the override
  • Chat override works — AI responds "Hey Jessica — nice to see you" confirming Rostrum Records account context is loaded
  • No prop drilling — email resolved via AccountOverrideSync → session storage → useVercelChat
  • Badge renders immediately from query param (no useEffect needed)

Without ?email=

  • No badge shown
  • Normal chat behavior unchanged

sweetmantech and others added 2 commits April 6, 2026 18:00
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Single source of truth for override state. Badge and useVercelChat
both consume useAccountOverride() context. Override persists across
page refreshes via session storage. Badge shows even after navigation.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

export function useAccountOverride() {
return useContext(AccountOverrideContext);
}
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SRP - create lib files so the provider has less than 100 lines of code.

sweetmantech and others added 2 commits April 6, 2026 18:09
Only treat 404 as "not found". Other HTTP errors (401, 500, etc.)
should surface so useQuery can retry or show error state.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Moved session storage read/write/clear to lib/accounts/accountOverrideStorage.ts.
Provider is now 86 lines.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SRP

  • move any functions with names different from the file name do a different lib file with the same file name as the function name.

Comment on lines +54 to +75
useEffect(() => {
if (emailParam === "clear") {
clearStoredAccountOverride();
setStored({ accountId: null, email: null });
return;
}
if (resolvedAccountId && email) {
setStoredAccountOverride(resolvedAccountId, email);
setStored({ accountId: resolvedAccountId, email });
}
}, [emailParam, email, resolvedAccountId]);

const clear = useCallback(() => {
clearStoredAccountOverride();
setStored({ accountId: null, email: null });
const params = new URLSearchParams(searchParams.toString());
params.delete("email");
const newPath = params.toString()
? `${window.location.pathname}?${params.toString()}`
: window.location.pathname;
router.replace(newPath);
}, [searchParams, router]);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can either of these be made more efficient with the use of the tanstack package? useQuery or useMutation?

- Split accountOverrideStorage.ts into 3 files matching function names
- Moved storage sync into useQuery queryFn, removed useEffect

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should these 3 libs be moved to

  • actual: lib/accounts/clearStoredAccountOverride.ts
  • suggested: lib/accounts/override/clearStoredAccountOverride.ts

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@sweetmantech sweetmantech merged commit 5c122a0 into test Apr 6, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants